﻿// =====================================================================
//
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =====================================================================
#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xrm.Sdk.XmlNamespaces;

#endregion

namespace Microsoft.Xrm.Sdk.Client.Protocols.Policy
{
	public sealed class BearerTokenTemplate : TokenTemplate
	{
		public static Boolean ExtractToken(XElement policy, TokenPolicy trustPolicy)
		{
			IEnumerable<XElement> bindingElements =
				from el in policy.Descendants(PublicNamespaces.SP + @"SignedSupportingTokens")
				select el;

			foreach (XElement bindingElement in bindingElements)
			{
				IEnumerable<XElement> issuedTokens =
					from el in bindingElement.Descendants(PublicNamespaces.SP + @"IssuedToken")
					select el;
				foreach (XElement issuedToken in issuedTokens)
				{
					RequestSecurityTokenTemplate requestToken = new RequestSecurityTokenTemplate();
					IEnumerable<XElement> requestSecurityTokenTemplates =
						from el in issuedToken.Descendants(PublicNamespaces.SP + @"RequestSecurityTokenTemplate")
						select el;
					if (requestSecurityTokenTemplates.Count() > 0)
					{
						foreach (XElement tokenTemplate in requestSecurityTokenTemplates)
						{
							IEnumerable<XElement> trustElements = tokenTemplate.Descendants();
							foreach (XElement trustElement in trustElements)
							{
								requestToken.SetPropertyValue(trustElement.Name.LocalName, trustElement.Value);
							}
						}
						trustPolicy.Tokens[KeyTypes.Bearer] = requestToken;
						trustPolicy.CredentialType = TokenServiceCredentialType.None;
						return true;
					}
				}
			}
			return false;
		}
	}
}
